#include "GPS/get_uav_location.hpp"
#include "com/com_connect.hpp"
#include "com/find_com.hpp"
#include "com/get_com_message.hpp"
#include "com/send_message_com.hpp"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext> // 添加头文件以解决 QQmlContext 不完整类型的问题

int main(int argc, char *argv[]) {
  QGuiApplication app(argc, argv);

  QQmlApplicationEngine engine;
  // 查找可用的串口
  Find_Com find_com;
  ComConnect com_connect;
  engine.rootContext()->setContextProperty("FindCom", &find_com);

  // 接收消息对象需要在GetUavLocation之前创建
  GetComMessage get_com_message(nullptr, com_connect.getSerialP());
  engine.rootContext()->setContextProperty("getComMessage", &get_com_message);

  // 获取uav位置 - 必须在engine.load(url)之前暴露
  GetUavLocation get_uav_location(nullptr, com_connect.getSerialP(),
                                  get_com_message.getMavlinkMessage());
  engine.rootContext()->setContextProperty("getUavLocation", &get_uav_location);

  // 加载qml文件
  const QUrl url(QStringLiteral("qrc:/test2/qml/Main.qml"));
  QObject::connect(
      &engine, &QQmlApplicationEngine::objectCreationFailed, &app,
      []() { QCoreApplication::exit(-1); }, Qt::QueuedConnection);
  engine.load(url);

  // 获取qml中选择的串口
  QObject *rootObject = engine.rootObjects().first();
  if (rootObject) {
    QObject::connect(
        rootObject, SIGNAL(backSelectComMes(QString, int, bool, int)),
        &com_connect, SLOT(initComPort(QString, int, bool, qint32)));
    QObject::connect(rootObject, SIGNAL(closeSelectCom()), &com_connect,
                     SLOT(closeCom()));

    // 更新父对象
    get_com_message.setParent(rootObject);
    get_uav_location.setParent(rootObject);
  }

  // 发送消息
  SendMessageCom send_message_com(rootObject, com_connect.getSerialP());
  QObject::connect(rootObject, SIGNAL(sendMessage(QString)), &send_message_com,
                   SLOT(sendMessage(QString)));
  // 发送心跳
  QObject::connect(rootObject, SIGNAL(sendHeartbeat()), &send_message_com,
                   SLOT(sendHeartbeat()));

  // 建立GPS消息接收和位置更新的连接
  QObject::connect(
      &get_com_message, SIGNAL(gpsMessageReceived(mavlink_message_t)),
      &get_uav_location, SLOT(updateMavlinkMessage(mavlink_message_t)));

  return app.exec();
}
